//
//  BKBangDiemViewController.m
//  I'm BKer
//
//  Created by Nguyen Van Hoa on 5/15/13.
//  Copyright (c) 2013 vanhoavn. All rights reserved.
//

#import "BKBangDiemViewController.h"
#import "BKHocKyInfoCell.h"
#import "BKBangDiemCell.h"

@interface BKBangDiemViewController ()

@end

@implementation BKBangDiemViewController

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        self.title = @"Bảng điểm";
        self.tabBarItem.image = [UIImage imageNamed:@"first"];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (NSInteger)valueForHKString: (NSString*) s
{
    int ip=0;
    NSInteger r=0;
    static int p10[]={1,10000,1000,100,10};
    for(int i=0;i<s.length;i++){
        unichar c = [s characterAtIndex:i];
        if(c>='0' && c<='9'){
            int cn = c - '0';
            if(ip<=4) r+=cn*p10[ip];
            ip++;
        }
    }
    return r;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    NSDictionary* arr = [BKStudentManager danhSachDiem];
    NSMutableArray* mHocKyMu = [[NSMutableArray alloc] init];
    NSMutableDictionary* mHocKyTTMu = [[NSMutableDictionary alloc] init];
    NSMutableDictionary* mHocKyDiemMu = [[NSMutableDictionary alloc] init];
    for(NSString* hocki in arr){
        [mHocKyMu addObject:hocki];
        [mHocKyTTMu setObject:[[[arr objectForKey:hocki] objectForKey:@"thongtin"] componentsJoinedByString:@"\n"] forKey:hocki];
        NSMutableArray* mHocKyDiem = [[NSMutableArray alloc] init];
        NSArray* dsDiem = [[arr objectForKey:hocki] objectForKey:@"chitiet"];
        for(NSDictionary* mon in dsDiem){
            [mHocKyDiem addObject:[NSDictionary
                                   dictionaryWithObjectsAndKeys:
                                   [mon objectForKey:@"ten"],@"monhoc",
                                   [NSString stringWithFormat:@"%@ - %@",
                                    [mon objectForKey:@"maso"],
                                    [mon objectForKey:@"nhom"]],@"mamonnhom",
                                   [NSString stringWithFormat:@"%@ TC", [mon objectForKey:@"tinchi"], nil],
                                   @"tinchi",
                                   [NSString stringWithFormat:@"KT:%02.2f | Thi:%02.2f | TK:%02.2f",
                                        [[mon objectForKey:@"diemkt"] floatValue],
                                        [[mon objectForKey:@"diemthi"] floatValue],
                                        [[mon objectForKey:@"diemtk"] floatValue],
                                    nil],
                                   @"diem",
                                   nil
                                   ]];
        }
        [mHocKyDiemMu setObject:mHocKyDiem forKey:hocki];
    }
    mHocKy = [mHocKyMu sortedArrayWithOptions:NSSortStable
                          usingComparator:^NSComparisonResult(NSString* a, NSString* b) {
                              int va=[self valueForHKString:a];
                              int vb=[self valueForHKString:b];
                              if(va==vb) return NSOrderedSame;
                              if(va>vb) return NSOrderedAscending;
                              return NSOrderedDescending;
    }];
    mHocKyThongTin = [NSDictionary dictionaryWithDictionary:mHocKyTTMu];
    mHocKyDiem = [NSDictionary dictionaryWithDictionary:mHocKyDiemMu];
    [self.tableView reloadData];
}


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [mHocKy count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(section>=0 && section<[mHocKy count]){
        return 1+[[mHocKyDiem objectForKey:[mHocKy objectAtIndex:section]] count];
    }
    return 0;
}
- (NSString*)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if(section>=0 && section<[mHocKy count]){
        return [mHocKy objectAtIndex:section];
    }
    return @"";
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    BOOL info = (indexPath.row+1==[self tableView:tableView numberOfRowsInSection:indexPath.section]);
    NSString *CellIdentifier = info?@"BKHocKyInfoCell":@"BKBangDiemCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[NSBundle mainBundle] loadNibNamed:CellIdentifier owner:nil options: nil] objectAtIndex:0];
    }
    if(info){
        BKHocKyInfoCell* mcell = cell;
        NSLog(@":: %@ %@",[mHocKy objectAtIndex:indexPath.section],[mHocKyThongTin objectForKey:[mHocKy objectAtIndex:indexPath.section]]);
        mcell.lblTxt.text=[mHocKyThongTin objectForKey:[mHocKy objectAtIndex:indexPath.section]];
    }else{
        BKBangDiemCell* mcell = cell;
        NSDictionary* dict = [[mHocKyDiem objectForKey:[mHocKy objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row];
        mcell.lblDiem.text=[dict objectForKey:@"diem"];
        mcell.lblNhomTo.text=[dict objectForKey:@"mamonnhom"];
        mcell.lblTC.text=[dict objectForKey:@"tinchi"];
        mcell.lblTen.text=[dict objectForKey:@"monhoc"];
    }
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section<0 || indexPath.section>=[mHocKy count]) return 0;
    BOOL info = (indexPath.row+1==[self tableView:tableView numberOfRowsInSection:indexPath.section]);
    if(info){
        if([[mHocKyThongTin objectForKey:[mHocKy objectAtIndex:indexPath.section]] length]<3) return 0;
    }
    return info?95.f:55.f;
}
/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Navigation logic may go here. Create and push another view controller.
    /*
     <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
     [self.navigationController pushViewController:detailViewController animated:YES];
     */
}

@end
